// API配置参数
export const API_KEY = "ragflow-IwZGQ0NDY4MGU1NjExZjBiMjY4MDI0Mm";
export const BASE_URL = "http://127.0.0.1";
export const CHAT_ID = "f596b90c130811f0bf8d0242ac120002";
export const JWT = "";

// OpenAI兼容API配置参数
export const OPENAI_API_KEY = "";
export const OPENAI_BASE_URL = "https://api.openai.com/v1";
export const OPENAI_MODEL = "gpt-3.5-turbo";

// 导入认证服务
import { isLoggedIn, saveUserData, getUserData } from "./auth";

// 获取自定义配置
export const getConfig = () => {
  try {
    // 优先从用户数据中获取配置
    if (isLoggedIn()) {
      const userConfig = getUserData("config");
      if (userConfig) {
        return {
          apiKey: userConfig.apiKey || API_KEY,
          baseUrl: userConfig.baseUrl || BASE_URL,
          chatId: userConfig.chatId || CHAT_ID,
          openaiApiKey: userConfig.openaiApiKey || OPENAI_API_KEY,
          openaiBaseUrl: userConfig.openaiBaseUrl || OPENAI_BASE_URL,
          openaiModel: userConfig.openaiModel || OPENAI_MODEL,
        };
      }
    }
    // 如果用户未登录或无配置，尝试从本地存储获取
    const savedConfig = localStorage.getItem("ragflow_config");
    if (savedConfig) {
      const config = JSON.parse(savedConfig);
      return {
        apiKey: config.apiKey || API_KEY,
        baseUrl: config.baseUrl || BASE_URL,
        chatId: config.chatId || CHAT_ID,
        openaiApiKey: config.openaiApiKey || OPENAI_API_KEY,
        openaiBaseUrl: config.openaiBaseUrl || OPENAI_BASE_URL,
        openaiModel: config.openaiModel || OPENAI_MODEL,
      };
    }
  } catch (e) {
    console.error("读取配置失败:", e);
  }

  // 返回默认配置
  return {
    apiKey: API_KEY,
    baseUrl: BASE_URL,
    chatId: CHAT_ID,
    openaiApiKey: OPENAI_API_KEY,
    openaiBaseUrl: OPENAI_BASE_URL,
    openaiModel: OPENAI_MODEL,
  };
};

// TODO: 完成得到JWT的函数
export const getJWTConfig = () => {
  return JWT;
};

// 保存配置
export const saveConfig = (config) => {
  try {
    // 保存到本地存储
    localStorage.setItem("ragflow_config", JSON.stringify(config));

    // 如果用户已登录，同时保存到用户数据中
    if (isLoggedIn()) {
      saveUserData("config", config);
    }

    return true;
  } catch (e) {
    console.error("保存配置失败:", e);
    return false;
  }
};
